//set appropriate directory
use "ChoiKarivMullerSilverman_actualandrandom.dta", clear


gen rev_emax=1-emax
gen rev_emax_placebo=1-emax_placebo



//generate the cdfs
sort tmi_nondiff
cumul tmi_nondiff, generate (cdf_tmi_nondiff)
sort tmi_nondiff_placebo
cumul tmi_nondiff_placebo, generate(cdf_tmi_nondiff_placebo)
sort rev_emax
cumul rev_emax, generate (cdf_rev_emax)
sort rev_emax_placebo
cumul rev_emax_placebo, generate(cdf_rev_emax_placebo)
sort tmi_combined_nondiff
cumul tmi_combined_nondiff, generate (cdf_tmi_combined_nondiff)
sort tmi_combined_nondiff_placebo
cumul tmi_combined_nondiff_placebo, generate (cdf_tmi_combined_nondiff_placebo)

sort tmi_eunondiff
cumul tmi_eunondiff, generate (cdf_tmi_eunondiff)
sort tmi_eunondiff_placebo
cumul tmi_eunondiff_placebo, generate (cdf_tmi_eunondiff_placebo)


//generate Figure 3 
//generate Figure 3a
gen diff=tmi_nondiff-rev_emax
hist diff,percent saving(Figure3a, replace)
graph export Figure3a.png, as(png)
//generate Figure 3b
twoway scatter cdf_tmi_nondiff tmi_nondiff, sort c(J)|| scatter cdf_tmi_nondiff_placebo tmi_nondiff_placebo, sort c(J)|| scatter cdf_rev_emax rev_emax, sort c(J)|| scatter cdf_rev_emax_placebo rev_emax_placebo, sort c(J) saving(Figure3b, replace)
graph export Figure3b.png, as(png)


//generate Figure 4
//generate Figure4a
twoway scatter cdf_tmi_nondiff tmi_nondiff, sort c(J)|| scatter cdf_tmi_combined_nondiff tmi_combined_nondiff, sort c(J)|| scatter cdf_tmi_eunondiff tmi_eunondiff, sort c(J) saving(Figure4a, replace)
graph export Figure4a.png, as(png)

//generate Figure4b
twoway scatter cdf_tmi_nondiff_placebo tmi_nondiff_placebo, sort c(J)|| scatter cdf_tmi_combined_nondiff_placebo tmi_combined_nondiff_placebo, sort c(J)|| scatter cdf_tmi_eunondiff_placebo tmi_eunondiff_placebo, sort c(J) saving(Figure4b, replace)
graph export Figure4b.png, as(png)


//generate Figure5
gen mratio=(tmi_eunondiff-tmi_combined_nondiff)/(tmi_eunondiff-tmi_nondiff)
gen mratio_placebo=(tmi_eunondiff_placebo-tmi_combined_nondiff_placebo)/(tmi_eunondiff_placebo-tmi_nondiff_placebo)
sort mratio
cumul mratio, generate (cdf_mratio)
sort mratio_placebo
cumul mratio_placebo, generate (cdf_mratio_placebo)
twoway scatter cdf_mratio mratio, sort c(J)|| scatter cdf_mratio_placebo mratio_placebo, sort c(J) saving(Figure5, replace)
graph export Figure5.png, as(png)

//spearman correlation between fdi and ccei
spearman rev_emax tmi_nondiff 

//counter # switches in ranking of ccei vs fdi in CKMS data
keep if actual==1
keep rev_emax tmi_nondiff
gen var=1
gen counter=_n
reshape wide tmi_nondiff rev_emax, i(var) j(counter)
gen num=0
gen den=0
forvalues i=1/1182{
forvalues j=`i+1'/1182{
replace num=num + 1 if (rev_emax`i'>rev_emax`j' & tmi_nondiff`i'<tmi_nondiff`j')| (rev_emax`i'<rev_emax`j' & tmi_nondiff`i'>tmi_nondiff`j')
replace den=den+1
}
}
 di num/den

 
